import 'package:flutter_account_book/utils/db/db_helper.dart';
import 'package:flutter_account_book/utils/db/entities/account_record.dart';
import 'package:flutter_account_book/utils/db/entities/pay_method.dart';
import 'package:flutter_account_book/utils/db/entities/record_type.dart';
import 'package:flutter_account_book/utils/eventbus.dart';
import 'package:flutter_account_book/utils/time.dart';
import 'package:get/get.dart';

import 'state.dart';

class AddRecordLogic extends GetxController {
  AddRecordState state = AddRecordState();

  late DateTime datetime;
  late RecordType recordType;
  late PayMethod pay;

  @override
  void onInit() {
    super.onInit();
    setDateTime(DateTime.now());
    loadData(0, first: true);
    _loadPay();
  }

  loadData(int isIncome, {first = false}) async {
    if (!first && state.isIncome.value == isIncome) {
      return;
    }
    state.isIncome.value = isIncome;
    state.list.value = await DbHelper.helper.recordTypeDao.flowAll(isIncome);
    setSelected(state.list.first);
  }

  _loadPay() async {
    state.payMethods.value = await DbHelper.helper.payMethodDao.flowAll();
    setPay(state.payMethods.first);
  }

  setPay(PayMethod payMethod) {
    pay = payMethod;
    state.payIcon.value = payMethod.iconPath ?? "";
    state.payName.value = payMethod.name;
  }

  setSelected(RecordType recordType) {
    this.recordType = recordType;
    state.selectedId.value = recordType.id!;
  }

  setDateTime(DateTime? datetime) {
    if (datetime != null) {
      this.datetime = datetime;
      state.dateString.value = formatDateTime(datetime);
    }
  }

  void clearZero() {
    state.isAdd.value = false;
    state.numberString.value = '';
  }

  /// 记账保存
  Future<void> record() async {
    if (state.numberString.isEmpty || state.numberString.value == '0.') {
      return;
    }
    state.isAdd.value = false;

    AccountRecord accountRecord = AccountRecord();
    accountRecord.recordTime = datetime.millisecondsSinceEpoch;
    accountRecord.createTime = DateTime.now().millisecondsSinceEpoch;
    accountRecord.updateTime = DateTime.now().millisecondsSinceEpoch;
    accountRecord.payMethod = pay.name;
    accountRecord.payMethodId = pay.id;
    accountRecord.remark = state.remark.value;
    accountRecord.recordType = recordType.name;
    accountRecord.recordTypeId = recordType.id!;
    accountRecord.isIncome = recordType.isIncome;
    accountRecord.amount = double.parse(state.numberString.value);
    accountRecord.id = await DbHelper.helper.accountRecordDao.getUnusedId();
    accountRecord.books = Get.arguments as int;
    accountRecord.save().then((_) {
      eventBus.fire(AddRecordEvent());
    });
  }

  void addNumber() {
    state.isAdd.value = false;
    List<String> numbers = state.numberString.split('+');
    double number = 0.0;
    for (String item in numbers) {
      if (item.isEmpty == false) {
        number += double.parse(item);
      }
    }
    String numberString = number.toString();
    if (numberString.split('.').last == '0') {
      numberString = numberString.substring(0, numberString.length - 2);
    }
    state.numberString.value = numberString;
  }

  void inputVerifyNumber(String number) {
    print('number: $number');
    //小数点精确分，否则不能输入
    //加法
    if (state.numberString.isEmpty) {
      //没输入的时候，不能输入+或者.
      if (number == '+') {
        return;
      }

      if (number == '.') {
        state.numberString.value += '0.';
        return;
      }

      state.numberString.value += number;
    } else {
      List<String> numbers = state.numberString.value.split('');
      if (numbers.length == 1) {
        // 当只有一个数字
        if (numbers.first == '0') {
          //如果第一个数字是0，那么输入其他数字和+不生效
          if (number == '.') {
            state.numberString.value += number;
          } else if (number != '+') {
            state.numberString.value = number;
          }
        } else {
          //第一个数字不是0 为1-9
          if (number == '+') {
            state.isAdd.value = true;
          }
          state.numberString.value += number;
        }
      } else {
        List<String> temps = state.numberString.value.split('+');
        if (temps.last.isEmpty && number == '+') {
          //加号
          return;
        }

        //拿到最后一个数字
        String lastNumber = temps.last;
        List<String> lastNumbers = lastNumber.split('.');
        if (lastNumbers.last.isEmpty && number == '.') {
          return;
        }
        if (lastNumbers.length > 1 &&
            lastNumbers.last.length >= 2 &&
            number != '+') {
          return;
        }

        if (number == '+') {
          state.isAdd.value = true;
        }
        state.numberString.value += number;
      }
    }
  }
}
